//
//  BanBu_PhotoAlbumViewController.m
//  BanBu
//
//  Created by Wang Xj on 13-9-7.
//
//

#import "BanBu_PhotoAlbumViewController.h"
#import <MediaPlayer/MediaPlayer.h>
#import "AppDataManager.h"
#import "BanBu_NavButton.h"
#import "BanBu_PhotoViewController.h"
#import "BanBu_ChatViewController.h"
#import "UIViewController+Animation.h"
#define SeletedImageTag 20001
#define videoFlagImgTag 20002

@interface BanBu_PhotoAlbumViewController ()

@end

@implementation BanBu_PhotoAlbumViewController
@synthesize type_file = _type_file;
- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = NSLocalizedString(@"HalfareaAlbume", nil);
    [self createBackButton];
    self.editing = NO;//默认编辑状态为NO
    
    self.videoFilePath = [[[[NSHomeDirectory() stringByAppendingPathComponent:@"Library"] stringByAppendingPathComponent:@"Caches"]stringByAppendingPathComponent:@"AlbumFolder"] stringByAppendingPathComponent:@"videoInfo.plist"];
    
    self.tableView.backgroundView = nil;
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    
    self.deleteVideoArray = [NSMutableArray arrayWithCapacity:10];
    self.videoArray = [NSMutableArray arrayWithCapacity:20];
    
    if ([FileManager fileExistsAtPath:self.videoFilePath])
    {
        self.videoArray = [NSMutableArray arrayWithContentsOfFile:self.videoFilePath];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)createBackButton
{
//    BanBu_NavButton *btn_return=[[BanBu_NavButton alloc] initWithButtonType:UIButtonCreatTypeBack];
//    btn_return.position = ButtonPositionLeft;
//    [btn_return addTarget:self action:@selector(popself) forControlEvents:UIControlEventTouchUpInside];
//    btn_return.titleLabel.font = [UIFont systemFontOfSize:14];
//    
//    UIBarButtonItem *bar_itemreturn = nil;
//    CGFloat btnLen = [NSLocalizedString(@"returnButton", nil) sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(100, 30)].width;
//    
//    btn_return.frame=CGRectMake(0, 0, btnLen+20, 30);
//    
//    [btn_return setTitle:NSLocalizedString(@"returnButton", nil) forState:UIControlStateNormal];
//    
//    bar_itemreturn=[[[UIBarButtonItem alloc] initWithCustomView:btn_return] autorelease];
//    
//    self.navigationItem.leftBarButtonItem = bar_itemreturn;
    
    
    BanBu_NavButton *actionButton=[[BanBu_NavButton alloc] initWithButtonType:UIButtonCreatTypeNormal];
    actionButton.position = ButtonPositionRight;
    actionButton.frame=CGRectMake(0, 7, 50, 30);
    actionButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [actionButton setTitle:NSLocalizedString(@"deleteButton", nil) forState:UIControlStateNormal];
    [actionButton addTarget:self action:@selector(editVideo:) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.rightBarButtonItem=[[[UIBarButtonItem alloc]initWithCustomView:actionButton]autorelease];
}

-(void)popself
{
    MyAppDataManager.chatuid = nil;
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return ceilf(self.videoArray.count/4.0);
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        
        for (int i = 1; i<5; i++)
        {
            UIButton * button1 = [UIButton buttonWithType:UIButtonTypeCustom];

            [button1 setFrame:CGRectMake(78*(i-1)+ 5.5, 5, 74, 74)];
            
            button1.tag = i;
            
            [button1 addTarget:self action:@selector(selectVideo:) forControlEvents:UIControlEventTouchUpInside];
            
            UIImageView * flagImage = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"palyBtn.png"]];
            flagImage.frame = CGRectMake(17, 22, 40, 40);
            
            flagImage.tag = videoFlagImgTag;
            [button1 insertSubview:flagImage atIndex:0];
            [flagImage release];
            [cell addSubview:button1];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    for (int i = 1; i<5; i++)
    {
        NSInteger index = indexPath.row * 4+i-1;
        UIButton * button = (UIButton *)[cell viewWithTag:i];
        UIImageView * flagImage = (UIImageView *)[button viewWithTag:videoFlagImgTag];
        
        if (index <self.videoArray.count)
        {
            UIImage * image =[UIImage imageWithContentsOfFile:[[self.videoArray objectAtIndex:index] valueForKey:@"thumbnailName"]];
                        
            image = [UIImage imageWithCGImage:CGImageCreateWithImageInRect(image.CGImage, CGRectMake(40, 0, 240, 240))];
            
            [button setBackgroundImage:image forState:UIControlStateNormal];
            button.hidden = NO;
            flagImage.hidden = NO;
            
            UILabel * lable = [[UILabel alloc]init];
            lable.text = [NSString stringWithFormat:@"%d",index];
            lable.alpha = 0;
            lable.tag = 100001;
            [button addSubview:lable];
        }
        else
        {
            [button setBackgroundImage:nil forState:UIControlStateNormal];
            button.hidden = YES;
            flagImage.hidden = YES;
        }
        UIImageView * selectedImageView =(UIImageView *)[button viewWithTag:SeletedImageTag];
        if (selectedImageView)
        {
            [selectedImageView removeFromSuperview];
        }
    }
    
    
    return cell;
}


#pragma mark - Table view delegate

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80;
}

//选择视频、预览
-(void)selectVideo:(UIButton *)sender
{
    UILabel * label = (UILabel *)[sender viewWithTag:100001];
    NSInteger index = [label.text integerValue];
    
    if(self.editing)
    {
        UIImageView * selectedImageView =(UIImageView *)[sender viewWithTag:SeletedImageTag];
        
        if (!selectedImageView)
        {
            UIImageView * selectedImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"CellSelected.png"]];
            selectedImageView.tag = SeletedImageTag;
            [sender addSubview:selectedImageView];
            [selectedImageView release];
            [self.deleteVideoArray addObject:[self.videoArray objectAtIndex:index]];
        }
        else
        {
            [selectedImageView removeFromSuperview];
            [self.deleteVideoArray removeObject:[self.videoArray objectAtIndex:index]];
        }
    }
    else
    {
        NSString * videName = [[self.videoArray objectAtIndex:index] valueForKey:@"video"];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(popToChat) name:@"videoAlbumPopToChat" object:nil];
        
        BanBu_PhotoViewController * photo = [[BanBu_PhotoViewController alloc]init];
        
        photo.url = videName;
        photo.picker = nil;
        photo.type = MediaMsgTypeVideo;
        photo.enablePost = YES;
        photo.type_file = _type_file;
        [self presentViewController:photo animated:YES];
        [photo release];
    }
}

-(void)popToChat
{
    [UIApplication sharedApplication].statusBarHidden = NO;
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleBlackOpaque;
    
    //修改：yinlinlin
    if (_type_file == FILE_KOOLALBUM)
    {
        [self.navigationController popViewControllerAnimated:YES];
        return;
    }
    
    //修改完成：yinlinlin
    
    BanBu_ChatViewController *chat = nil;
    for(UIViewController *vc in [self.navigationController viewControllers])
        if([vc isKindOfClass:[BanBu_ChatViewController class]])
        {
            chat = (BanBu_ChatViewController *)vc;
            break;
        }
    if(chat)
    {
        [self.navigationController popToViewController:chat animated:YES];
    }else
    {
        BanBu_ChatViewController *chat=[[BanBu_ChatViewController alloc]init];
        
        [self.navigationController pushViewController:chat animated:YES];
        [chat release];
    }
}

//编辑
-(void)editVideo:(UIButton *)sender
{
    self.editing =!self.editing;
    if (self.editing)
    {
        [sender setTitle:NSLocalizedString(@"finishButton", nil) forState:UIControlStateNormal];
    }
    else
    {
        [sender setTitle:NSLocalizedString(@"deleteButton", nil) forState:UIControlStateNormal];
        
        if (!self.deleteVideoArray.count)
        {
            return;
        }
        
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_async(queue, ^{
            
            for (NSDictionary * dic in self.deleteVideoArray)
            {
                [FileManager removeItemAtPath:[dic valueForKey:@"videoName"] error:nil];
                [FileManager removeItemAtPath:[dic valueForKey:@"thumbnailName"] error:nil];
            }
            
            [self.videoArray removeObjectsInArray:self.deleteVideoArray];
            [self.videoArray writeToFile:self.videoFilePath atomically:YES];
            [self.deleteVideoArray removeAllObjects];
            
            dispatch_sync(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
            });
        });        
    }
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"videoAlbumPopToChat" object:nil];
    [_videoArray release],_videoArray = nil;
    [_deleteVideoArray release],_deleteVideoArray = nil;
    [super dealloc];
}
@end
